import java.util.LinkedList;
import java.util.Queue;

class Solution {
    int[] dx = {0,0,1,-1};
    int[] dy = {1,-1,0,0};
    public int numEnclaves(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        boolean[][] vis = new boolean[m][n];
        int total = 0;
        Queue<int[]> queue = new LinkedList<>();
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                if(grid[i][j] == 1){
                    total++;
                    if(i == 0 || i == m - 1 || j == 0 || j == n - 1){
                        queue.offer(new int[] {i, j});
                        vis[i][j] = true;
                    }
                }
            }
        }

        int size = queue.size();
        while(!queue.isEmpty()){
            int[] point = queue.poll();
            int a = point[0];
            int b = point[1];
            for(int i = 0; i < 4; i++){
                int x = a + dx[i];
                int y = b + dy[i];
                if(x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1 && !vis[x][y]){
                    size++;
                    queue.offer(new int[] {x, y});
                    vis[x][y] = true;
                }
            }
        }

        return total - size;
    }
}